package com.longy.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@Slf4j
@WebFilter
@Order(1)
public class TraceIdFilter implements Filter {

    private static final String TRACE_ID_HEADER = "X-Trace-Id";
    private static final String TRACE_ID_MDC_KEY = "traceId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("TraceIdFilter==init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String traceId = httpRequest.getHeader(TRACE_ID_HEADER);

            if (traceId == null || traceId.isEmpty()) {
                // 如果没有，自己生成一个
                traceId = UUID.randomUUID().toString().replace("-", "");
            }

            // 放到 MDC 中
            MDC.put(TRACE_ID_MDC_KEY, traceId);

            // 同时把 TraceId 设置回响应头，便于调试
            if (response instanceof javax.servlet.http.HttpServletResponse) {
                ((javax.servlet.http.HttpServletResponse) response).setHeader(TRACE_ID_HEADER, traceId);
            }

            chain.doFilter(request, response);
        } finally {
            // 清理，防止线程复用导致 TraceId 泄露
            MDC.remove(TRACE_ID_MDC_KEY);
        }
    }

    @Override
    public void destroy() {
        log.info("TraceIdFilter==destroy");
    }
}
